/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CambioClave.java
 *
 * Created on 12/12/2012, 17:53:12
 */

package IU;

import Controladores.CtrlSeguridadusr;
import Controladores.CtrlUsuario;
import Entidades.Operariorol;
import Entidades.Seguridadusr;
import Entidades.Usuario;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import utiles.Validador;

/**
 *
 * @author puflitos
 */
public class CambioClave extends javax.swing.JFrame {
CtrlUsuario controladorusr;
CtrlSeguridadusr ctrlseguridad;
  Validador validador;
  Seguridadusr segur;

    private String fechaAlta;
    /** Creates new form CambioClave */
    public CambioClave() {
        initComponents();
        controladorusr = new CtrlUsuario();
        ctrlseguridad = new CtrlSeguridadusr();
        segur = new Seguridadusr();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel5 = new javax.swing.JPanel();
        jTextFieldnombreusuario = new javax.swing.JTextField();
        jPasswordFieldcontrasenia = new javax.swing.JPasswordField();
        jPasswordFieldrepetircontrasenia = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jButtonGuardar = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldtextoseguridad = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jTextFieldnombreusuario1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        Salir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED), "Ingrese Datos de Usuario", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 3, 11), new java.awt.Color(102, 0, 102))); // NOI18N

        jTextFieldnombreusuario.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jPasswordFieldcontrasenia.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jPasswordFieldrepetircontrasenia.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jLabel4.setFont(new java.awt.Font("Segoe UI", 1, 11));
        jLabel4.setText("Usuario Actual:");

        jLabel2.setFont(new java.awt.Font("Segoe UI", 1, 11));
        jLabel2.setText("Nueva Contraseña:");

        jLabel10.setFont(new java.awt.Font("Segoe UI", 1, 11));
        jLabel10.setText("Repetir Contraseña:");

        jButtonGuardar.setFont(new java.awt.Font("Segoe UI", 3, 12));
        jButtonGuardar.setForeground(new java.awt.Color(102, 0, 102));
        jButtonGuardar.setText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel6.setText("Txt Seguridad: ");

        jTextFieldtextoseguridad.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jLabel3.setForeground(new java.awt.Color(204, 0, 0));
        jLabel3.setText("*");

        jLabel5.setForeground(new java.awt.Color(204, 0, 0));
        jLabel5.setText("*");

        jLabel8.setFont(new java.awt.Font("Segoe UI", 1, 11));
        jLabel8.setText(" Usuario Nuevo:");

        jTextFieldnombreusuario1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel10)
                    .addComponent(jLabel6)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPasswordFieldcontrasenia, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                            .addComponent(jTextFieldtextoseguridad, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                            .addComponent(jPasswordFieldrepetircontrasenia, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                            .addComponent(jTextFieldnombreusuario, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel3))
                        .addGap(105, 105, 105)
                        .addComponent(jButtonGuardar)
                        .addContainerGap())
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(jTextFieldnombreusuario1, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                        .addGap(210, 210, 210))))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(101, 101, 101)
                .addComponent(jButtonGuardar)
                .addContainerGap(56, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap(18, Short.MAX_VALUE)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldnombreusuario1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldnombreusuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel5))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jPasswordFieldcontrasenia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel10)
                            .addComponent(jPasswordFieldrepetircontrasenia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jTextFieldtextoseguridad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(23, 23, 23))
        );

        jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 11));
        jLabel1.setForeground(new java.awt.Color(204, 0, 0));
        jLabel1.setText("Ingrese solo caracteres");

        jLabel7.setForeground(new java.awt.Color(204, 0, 0));
        jLabel7.setText("*");

        Salir.setFont(new java.awt.Font("Segoe UI", 3, 12));
        Salir.setForeground(new java.awt.Color(102, 0, 102));
        Salir.setText("Salir");
        Salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(9, 9, 9)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 472, Short.MAX_VALUE)
                .addComponent(Salir)
                .addGap(20, 20, 20))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 129, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel7))
                        .addGap(52, 52, 52))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(Salir)
                        .addGap(39, 39, 39))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed
        try {
            String nuevous = jTextFieldnombreusuario1.getText();
            String us = jTextFieldnombreusuario.getText();
            String txtseguro = jTextFieldtextoseguridad.getText();
            Usuario u = controladorusr.buscarUsuarioNombreUsuario(us);
            Operariorol operol = new Operariorol();
            operol = u.getOperariorol();
            // Obtener el password
            char[] passArray = jPasswordFieldcontrasenia.getPassword();
            char[] repassArray = jPasswordFieldrepetircontrasenia.getPassword();
            // Convertir el password a String
            String pass = new String(passArray);
            String repass = new String(repassArray);
            if (verifica(pass, repass)) {
                //si los datos ingresados por el usuario son correctos, crea un usuario con los datos de entrada
                ///////////////////
                try {
                    String passencriptado = encriptar(pass);
                    System.out.println("pass enc" + passencriptado);
                     fechaAlta = Validador.getInstance().obtenerFechaSistema();
                    u.setContrasenia(passencriptado);
                    u.setFechaalta(fechaAlta);
                    u.setNombre(nuevous);
                    controladorusr.modificarUsuario(u);

                    segur.setIdusuario(u);
                    segur.setOperariorol(operol);
                    segur.setTextoseguro(txtseguro);
                    segur.setIdSeguridadUsr(segur.getIdSeguridadUsr());

                    ctrlseguridad.modificar(segur);


                    JOptionPane.showMessageDialog(this, "Modificación realizada", "Usuario / Contraseña", JOptionPane.INFORMATION_MESSAGE);

                } catch (Exception ex) {
                       JOptionPane.showMessageDialog(this, "Usuario no encontrado", "Error", JOptionPane.ERROR_MESSAGE);
                }
                //////////////////////////
                //////////////////////////
            }
        } catch (Exception ex) {
           JOptionPane.showMessageDialog(this, "Usuario no encontrado", "Error", JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_jButtonGuardarActionPerformed

    private void SalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SalirActionPerformed
dispose();        // TODO add your handling code here:
    }//GEN-LAST:event_SalirActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CambioClave().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Salir;
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPasswordField jPasswordFieldcontrasenia;
    private javax.swing.JPasswordField jPasswordFieldrepetircontrasenia;
    private javax.swing.JTextField jTextFieldnombreusuario;
    private javax.swing.JTextField jTextFieldnombreusuario1;
    private javax.swing.JTextField jTextFieldtextoseguridad;
    // End of variables declaration//GEN-END:variables

    private boolean verifica(String contrasenia, String repass) {
        boolean ver = false;
        if (contrasenia.equals("") || repass.equals("")) {
            JOptionPane.showMessageDialog(this, "Debe completar todos los datos, la contraseña no debe tener números!", "Error", JOptionPane.ERROR_MESSAGE);
        } else if (!validador.getInstance().passwrd(contrasenia)) {
            JOptionPane.showMessageDialog(this, "La contraseña debe ser mayor de 8 caracteres y menor a 15!", "Error", JOptionPane.ERROR_MESSAGE);
            System.out.println("passwrd contrasenia");
        } else if (!validador.getInstance().repassword(contrasenia, repass)) {
            JOptionPane.showMessageDialog(this, "La contraseña y la repetición de contraseña no son iguales, Ingrese nuevamente contraseña y repetición de contraseña!", "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            ver = true;
        }
        return ver;
    }//fin clase



    public String encriptar(String info_a_encriptar) {

              String abc1 = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ";
            //Variable que contendrá la información encriptada
        String info_encriptada = "";
        //variable
        Boolean cambio = false;
        //Bucle for mientras i sea menor al largo de la cadena a encriptar
        for (int i = 0; i < info_a_encriptar.length(); i++) {
            //Bucle mientras j sea menor al patron impuesto en la variable abc1
            for (int j = 0; j < abc1.length(); j++) {
                //Si la letra es igual a una de las letras del patrón.
                if (info_a_encriptar.charAt(i) == abc1.charAt(j)) {
                    //Cambiamos a true la variable boolean
                    cambio = true;
                    //Condicionales para no pasarse del total de letras del patrón.
                    if ((j == 24) || (j == 25) || (j == 26) || (j == 51) || (j == 52) || (j == 53)) {
                        //si el indice j es igual a estos límites
                        //Asignamos encriptando esta letra el valor del array abc1 de j menos 24
                        info_encriptada = info_encriptada + abc1.charAt(j - 24);
                    } else {
                        //Sino fuera así le asignamos el valor del array abc1 de j mas 3
                        info_encriptada = info_encriptada + abc1.charAt(j + 3);
                    }
                    //El valor de j lo ponemos a 53 y terminamos el bucle for
                    j = 53;
                }
            }
            //Si cambio es igual a false
            if (!cambio) {
                //Cargamos en la variable que contendrá el resultado el valor del caracter
                //de la info a encriptar
                info_encriptada = info_encriptada + info_a_encriptar.charAt(i);
            }
            //Damos a la variable boolean el valor false
            cambio = false;
        }
        //Si se termino de recorrer la palabra, frase o archivo enviado...
        //Damos a la variable original enviada a la función el valor de la variable
        //que contiene la encriptación.
        info_a_encriptar = info_encriptada;
        //Retornamos dicho valor.
        return info_a_encriptar;
    }


}
